package com.aiyige.page.my.buy;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiyige.R;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventLastPlayProgressUpdate;
import com.aiyige.model.PlayProgressModel;
import com.aiyige.model.enums.GoodsType;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.request.MyBuyRequest;
import com.aiyige.model.resource.UserResource;
import com.aiyige.model.response.MyBuyListResponse;
import com.aiyige.page.my.buy.adapter.MyBuyAdapter;
import com.aiyige.page.my.order.model.ScreenEntity;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.widget.CommonDataView;
import com.vondear.rxtools.RxKeyboardTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;

public class MyBuyDataPage extends BaseFragment implements CommonDataView.RetrofitStub {


    private String pageType;
    @BindView(R.id.cdv)
    CommonDataView cdv;
    MyBuyAdapter adapter;

    ScreenEntity screenEntity;

    public Callback getCallback() {
        return callback;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    Callback callback;

    public MyBuyDataPage() {
    }

    public String getPageTitle() {
        return GoodsType.getValueByKey(pageType);
    }

    public String getPageType() {
        return pageType;
    }

    public void setPageType(String pageType) {
        this.pageType = pageType;
    }

    public static MyBuyDataPage newInstance(String pageType, Callback callback) {
        MyBuyDataPage fragment = new MyBuyDataPage();
        fragment.setPageType(pageType);
        fragment.setAutoRegisterEventBus(true);
        fragment.setCallback(callback);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_common_data, container, false);
        ButterKnife.bind(this, view);
        adapter = new MyBuyAdapter();
        adapter.setSubject(pageType);
        cdv.config(adapter, this);
        cdv.addItemDecoration(1, R.color.zwcolor_gray_e3e3e3);
        cdv.setRecyclerViewBgColor(ContextCompat.getColor(getActivity(), R.color.zwcolor_gray_f4f8f9));

        return view;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventBusUpdateLastPlayProgress(EventLastPlayProgressUpdate eventBuss) {
        Log.i("xiachaoPlayerIndex",eventBuss.toString());
        if (adapter != null && !ListUtil.isEmpty(adapter.getData())) {
            for (UserResource userResource : adapter.getData()) {
                PlayProgressModel playProgressModel = null;
                if (!ListUtil.isEmpty(userResource.getStudyProgressBackup())) {
                    playProgressModel = userResource.getStudyProgressBackup().get(0);
                }
                // 确认是同一个资源
                Moment myMoment = null;
                if (!ListUtil.isEmpty(userResource.getResourceBackup())) {
                    myMoment = userResource.getResourceBackup().get(0);
                }
                String momentId = myMoment != null ? myMoment.getId():null;
                if (!TextUtils.isEmpty(momentId) && eventBuss != null && eventBuss.getResourceId() != null) {
                    if (eventBuss.getResourceId().equals(momentId)
                            && eventBuss.getProgress() > 0) {
                        if (playProgressModel == null) {
                            playProgressModel = new PlayProgressModel();
                            userResource.setStudyProgressBackup(Arrays.asList(playProgressModel));
                        }
                        playProgressModel.setProgress(eventBuss.getProgress());
                        playProgressModel.setStage(eventBuss.getStage());
                        break;
                    }
                }
            }
            adapter.notifyDataSetChanged();
        }
    }






    private String getTime() {
        return screenEntity != null ? screenEntity.getTime() : "";
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        return MyBuyRequest.newBuilder().resourceType(pageType).owner(AccountUtil.getCurrentUser().getId()).pageNum(currentPage).keyWord(getCallback().getSearchValue()).build();
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            MyBuyListResponse homeResponse = JsonUtil.toObject(respJson, MyBuyListResponse.class);
            if (ListUtil.isEmpty(homeResponse.getContent())) {
                resultList.addAll(homeResponse.getContent());
                return new CommonDataView.HandleResult(homeResponse.isLast());
            } else {
                String keyword = getCallback().getSearchValue();
                for (UserResource userResource : homeResponse.getContent()) {
                    try {
                        userResource.getResourceBackup().get(0).setTitle(HighLightWordUtil.highLight(userResource.getResourceBackup().get(0).getTitle(), keyword));
                    } catch (Exception e) {

                    }
                }
                resultList.addAll(homeResponse.getContent());
                return new CommonDataView.HandleResult(homeResponse.isLast());
            }

        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    @Override
    protected void initData() {
        cdv.doRefreshRequest();
    }

    public interface Callback {
        String getSearchValue();
    }

    public void refresh() {
        if (cdv == null) {
            return;
        }
        cdv.refresh();
        RxKeyboardTool.hideSoftInput(getActivity());
    }

}
